package com.hepinghospital.user.ui.fragment;

import android.annotation.SuppressLint;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hepinghospital.user.R;
import com.hepinghospital.user.base.BaseFragment;
import com.hepinghospital.user.ui.PayActivity;
import com.hepinghospital.user.ui.widget.CustomPopWindow;
import com.hepinghospital.user.util.ImageLoaderHelper;
import com.hepinghospital.user.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.observer.BaseObserver;
import com.rest.response.CloudDoctorResponse;
import com.rest.response.DicResponse;
import com.rest.response.Doctor;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.DpUtil;
import jz.joyoung.robot.util.TimeUtil;
import jz.joyoung.robot.util.UIConstants;
import jz.joyoung.robot.util.UtilString;


/**
 * Created by HP on 2020/2/20.
 */

@Deprecated
public class BookDoctorByDateFragment extends BaseFragment {

    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    @BindView(R.id.doctor_recyclerView)
    RecyclerView doctor_recyclerView;
    @BindView(R.id.date_recyclerView)
    RecyclerView date_recyclerView;
    @BindView(R.id.btn_zhichen)
    TextView btn_zhichen;
    @BindView(R.id.btn_keshi)
    TextView btn_keshi;

    private List<DateTime> dateList = new ArrayList();
    private List<Doctor> doctorList = new ArrayList<>();


    private DoctorAdapter doctorAdapter;

    private int current = 1;
    private String currentString = "", currentId = "";

    public static BookDoctorByDateFragment newInstance() {
        Bundle args = new Bundle();
        BookDoctorByDateFragment fragment = new BookDoctorByDateFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_book_docot_date;
    }

    @Override
    protected void initView() {
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        doctor_recyclerView.setLayoutManager(manager);
        doctorAdapter = new DoctorAdapter();
        doctor_recyclerView.setAdapter(doctorAdapter);
        doctor_recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(@NotNull Canvas c, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }

            @Override
            public void getItemOffsets(@NotNull Rect outRect, @NotNull View view, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = DpUtil.dip2px(mContext, 8);
            }
        });
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(refreshlayout -> {
            doctorList.clear();
            initData();
        });
        refreshLayout.setOnLoadMoreListener(refreshlayout -> {
            current++;
            getDoctorList(currentId, currentString, "", "");
        });
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        date_recyclerView.setLayoutManager(linearLayoutManager);
        DateAdapter dateAdapter = new DateAdapter();
        date_recyclerView.setAdapter(dateAdapter);
        date_recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(@NotNull Canvas c, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }

            @Override
            public void getItemOffsets(@NotNull Rect outRect, @NotNull View view, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.right = DpUtil.dip2px(mContext, 8);
            }
        });

    }

    @Override
    protected void initData() {
        current = 1;
        getDoctorList(currentId, currentString, "", "");
        getDateList();
    }


    class DoctorAdapter extends RecyclerView.Adapter<DoctorAdapter.Holder> {

        @NotNull
        @Override
        public Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            Holder myHolder;
            myHolder = new Holder(LayoutInflater.from(mContext).inflate(R.layout.item_book_doctor_online, parent, false));
            return myHolder;
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(Holder holder, final int position) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundleCloud = new Bundle();
                    bundleCloud.putSerializable(UIConstants.OBJ_Doctor, doctorList.get(position));
                    bundleCloud.putInt(UIConstants.PayActivity_TYPE_FLAG, UIConstants.PayActivity_TYPE_1);
                    startActivity(PayActivity.class, bundleCloud);
                }
            });
            holder.tv_level.setText(doctorList.get(position).jobTitleName);
            holder.tv_skill.setText("擅长:" + doctorList.get(position).docGoodAtNames);
            holder.tv_star.setText(doctorList.get(position).score);
            holder.tv_name.setText(doctorList.get(position).docName);
            ImageLoaderHelper.getInstance().GlideCircleImageLoader(mContext, doctorList.get(position).thumbnailUrl, holder.img_head);
            if (doctorList.get(position).isPrescription == 1) {
                holder.tv_recipel.setText("处方");
                holder.tv_recipel.setTextColor(Color.parseColor("#ff209187"));
            } else {
                holder.tv_recipel.setText("非处方");
                holder.tv_recipel.setTextColor(Color.parseColor("#ffd5d5d5"));
            }
            if (!UtilString.isEmpty(doctorList.get(position).deptName)) {
                holder.tv_deptName.setText(doctorList.get(position).deptName);
            } else {
                holder.tv_deptName.setVisibility(View.GONE);
            }
            holder.ratingBar.setRating(Float.parseFloat(doctorList.get(position).score));
        }

        @Override
        public int getItemCount() {
            return doctorList.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_name, tv_level, tv_recipel, tv_deptName, tv_skill, tv_star;
            ImageView img_head;
            RatingBar ratingBar;

            public Holder(View itemView) {
                super(itemView);
                tv_name = itemView.findViewById(R.id.tv_name);
                tv_level = itemView.findViewById(R.id.tv_level);
                tv_recipel = itemView.findViewById(R.id.tv_recipel);
                tv_deptName = itemView.findViewById(R.id.tv_deptName);
                tv_skill = itemView.findViewById(R.id.tv_skill);
                tv_star = itemView.findViewById(R.id.tv_star);
                img_head = itemView.findViewById(R.id.img_head);
                ratingBar = itemView.findViewById(R.id.ratingBar);
            }
        }
    }


    class DateAdapter extends RecyclerView.Adapter<DateAdapter.Holder> {

        @NotNull
        @Override
        public Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            Holder myHolder;
            myHolder = new Holder(LayoutInflater.from(mContext).inflate(R.layout.item_book_date, parent, false));
            return myHolder;
        }

        @Override
        public void onBindViewHolder(@NotNull Holder holder, final int position) {
            if (dateList.get(position).isSelect) {
                holder.tv_date.setTextColor(getResources().getColor(R.color.mainBlue));
                holder.tv_time.setTextColor(getResources().getColor(R.color.mainBlue));
                holder.tv_all.setTextColor(getResources().getColor(R.color.mainBlue));
                holder.container.setBackgroundResource(R.drawable.item_bg_green);
            } else {
                holder.tv_date.setTextColor(getResources().getColor(R.color.commonGrey));
                holder.tv_time.setTextColor(getResources().getColor(R.color.commonGrey));
                holder.tv_all.setTextColor(getResources().getColor(R.color.commonGrey));
                holder.container.setBackgroundResource(R.drawable.item_bg_grey);
            }
            if (position == 0) {
                holder.tv_date.setVisibility(View.INVISIBLE);
                holder.tv_time.setVisibility(View.INVISIBLE);
                holder.tv_all.setVisibility(View.VISIBLE);
            } else {
                holder.tv_date.setVisibility(View.VISIBLE);
                holder.tv_time.setVisibility(View.VISIBLE);
                holder.tv_all.setVisibility(View.INVISIBLE);
                holder.tv_date.setText(dateList.get(position).date);
                holder.tv_time.setText(dateList.get(position).time);
            }
            holder.itemView.setOnClickListener(v -> {
                if (position == 0) {
                    currentString = "";
                    getDoctorList(currentId, currentString, "", "");
                } else {
                    getDoctorList(currentId, currentString, dateList.get(position).allDate, dateList.get(position).timeId);
                }
                for (int i = 0; i < dateList.size(); i++) {
                    dateList.get(i).isSelect = false;
                }
                dateList.get(position).isSelect = true;
                notifyDataSetChanged();
            });
        }

        @Override
        public int getItemCount() {
            return dateList.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_date, tv_time, tv_all;
            RelativeLayout container;

            public Holder(View itemView) {
                super(itemView);
                tv_date = itemView.findViewById(R.id.tv_date);
                tv_time = itemView.findViewById(R.id.tv_time);
                tv_all = itemView.findViewById(R.id.tv_all);
                container = itemView.findViewById(R.id.container);
            }
        }
    }


    private void getDateList() {
        dateList.add(new DateTime());
        for (int i = 1; i < 15; i++) {
            for (int j = 0; j < 2; j++) {
                Calendar c = Calendar.getInstance();
                DateTime dateTime = new DateTime();
                int day1 = c.get(Calendar.DATE);
                c.set(Calendar.DATE, day1 + i);
                dateTime.date = TimeUtil.getTime(c.getTime());
                dateTime.allDate = TimeUtil.getAllTime(c.getTime());
                if (j == 0) {
                    dateTime.time = getDay(c) + "上午";
                    dateTime.timeId = "am";
                } else {
                    dateTime.time = getDay(c) + "下午";
                    dateTime.timeId = "pm";
                }
                dateList.add(dateTime);
            }
        }
        dateList.get(0).isSelect = true;
    }


    private void getDoctorList(String id, String content, String date, String time) {
        RestProxy.getInstance().getCloudDoctorList(id, content, date, time, "3", current + "", "10", "0","0","1", new Observer<CloudDoctorResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(CloudDoctorResponse doctorResponse) {
                doctorList.clear();
                doctorList.addAll(doctorResponse.records);
                doctorAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
                refreshLayout.finishRefresh(false);
            }

            @Override
            public void onComplete() {
                refreshLayout.finishRefresh(true);
            }
        });
    }

    static class DateTime {
        public String date;
        public String time;
        public String timeId;
        public String allDate;
        public boolean isSelect = false;
    }


    private String getDay(Calendar c) {
        String[] arr = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        return arr[c.get(Calendar.DAY_OF_WEEK) - 1];
    }

    private List<DicResponse> list = new ArrayList<>();
    private CustomPopWindow mPopWindow;
    private AddMedicineAdapter adapter;

    @OnClick(R.id.btn_keshi)
    void btn_keshi() {
        showPopListView(btn_keshi, 0);
    }

    @OnClick(R.id.btn_zhichen)
    void btn_zhichen() {
        showPopListView(btn_zhichen, 1);

    }

    private void showPopListView(View view, int type) {
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.pop_window, null);
        RecyclerView recyclerView = contentView.findViewById(R.id.recyclerView);
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        adapter = new AddMedicineAdapter(type);
        recyclerView.setAdapter(adapter);
//        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
//            @Override
//            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
//                super.onDraw(c, parent, state);
//            }
//
//            @Override
//            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
//                super.getItemOffsets(outRect, view, parent, state);
//                outRect.bottom = DpUtil.dip2px(activity, 1);
//            }
//        });
        if (type == 1) {
            getDictList();
        } else {
            getDepartmentList();
        }

        //创建并显示popWindow
        mPopWindow = new CustomPopWindow.PopupWindowBuilder(mContext)
                .setView(contentView)
                .setTouchable(true)
                .size(ViewGroup.LayoutParams.MATCH_PARENT, DpUtil.dip2px(mContext, 300)) // 显示大小
                .create()
                .showAsDropDown(view, 0, 0, Gravity.CENTER);
    }


    class AddMedicineAdapter extends RecyclerView.Adapter<AddMedicineAdapter.Holder> {

        int type;

        AddMedicineAdapter(int type) {
            this.type = type;
        }

        @NotNull
        @Override
        public Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            Holder myHolder;
            myHolder = new Holder(LayoutInflater.from(mContext).inflate(R.layout.item_textview, parent, false));
            return myHolder;
        }

        @Override
        public void onBindViewHolder(Holder holder, final int position) {
            holder.itemView.setOnClickListener(v -> {
                if (type == 1) {
                    //按照职称查询
                    currentString = list.get(position).name;
                    btn_zhichen.setText(list.get(position).name);
                    getDoctorList(currentId, currentString, "", "");
                    mPopWindow.dissmiss();
                } else {
                    currentId = list.get(position).id;
                    btn_keshi.setText(list.get(position).name);
                    getDoctorList(currentId, currentString, "", "");
                    mPopWindow.dissmiss();
                }
            });
            holder.tv_name.setText(list.get(position).name);
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_name;

            public Holder(View itemView) {
                super(itemView);
                tv_name = itemView.findViewById(R.id.text);
            }
        }
    }

    private void getDictList() {
        RestProxy.getInstance().getDicList(new BaseObserver<List<DicResponse>>() {

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onSuccess(List<DicResponse> result) {
                list.clear();
                list.addAll(result);
                adapter.notifyDataSetChanged();
            }
        });
    }

    private void getDepartmentList() {
        RestProxy.getInstance().getDepartment2List(new Observer<List<DicResponse>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(List<DicResponse> dicResponses) {
                list.clear();
                list.addAll(dicResponses);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable e) {
                refreshLayout.finishRefresh(false);
                ToastUtil.onError(mContext, e);

            }

            @Override
            public void onComplete() {
                refreshLayout.finishRefresh(true);
            }
        });
    }
}
